﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoundSynth
{
    class MathUtils
    {
        public static int ppcm(int[] numbers)
        {
            if (numbers.Length == 0) return 0;
            if (numbers.Length < 2) return (int)numbers[0];
            return ppcm(numbers[0], ppcm(numbers.Skip(1).ToArray()));
        }
        public static int ppcm(int a, int b)
        {
            if (b == 0) return a;
            if (a == 0) return b;
            return (a*b)/ pgcd(a, b);
        }

        public static int pgcd(int[] numbers)
        {
            if (numbers.Length == 0) return 0;
            if (numbers.Length < 2) return (int)numbers[0];
            return pgcd(numbers[0], pgcd(numbers.Skip(1).ToArray()));
        }
        public static int pgcd(int a, int b)
        {
            int firstNumber = (int)a;
            int secondNumber = (int)b;

            int gcd = 0;
            if (firstNumber > secondNumber)
            {
                var aa = secondNumber;
                secondNumber = firstNumber;
                firstNumber = aa;
            }

            while (secondNumber != 0)
            {
                gcd = firstNumber % secondNumber;
                firstNumber = secondNumber;
                if (gcd == 0)
                {
                    gcd = secondNumber;
                    secondNumber = 0;  // cleanly exit the loop
                    //break;  // I do not like doing this.
                }
                else
                {
                    secondNumber = gcd; // do this only if we need to loop again
                }
            }
            return gcd;
        }
    }
}
